﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
namespace Utils
{
    public class Cookie
    {
        public static string GetCookieValue(string cookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie != null) return cookie.Value.ToString();
            else return string.Empty;
        }

        public static HttpCookie GetCookie(string cookieName, string cookeiPrefix = "")
        {
            return HttpContext.Current.Request.Cookies[cookeiPrefix + cookieName];
        }
        public static void SaveCookieValue(string cookieName, string cookieValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie == null) cookie = new HttpCookie(cookieName, cookieValue);
            cookie.Value = cookieValue;
            HttpContext.Current.Response.SetCookie(cookie);
        }
        public static void SaveCookieValue(string cookieName, string cookieValue, DateTime? expirationDate = null, string rootDomain = "", string cookiePrefix = "")
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiePrefix + cookieName];
            if (cookie == null) cookie = new HttpCookie(cookiePrefix + cookieName, cookieValue);
            if (!string.IsNullOrEmpty(rootDomain))
                cookie.Domain = rootDomain;
            cookie.Value = cookieValue;
            if (expirationDate != null && expirationDate != DateTime.MaxValue)
            {
                cookie.Expires = (DateTime)expirationDate;
            }
            HttpContext.Current.Response.SetCookie(cookie);

        }

        public static T GetSessionCookie<T>(string cookieName)
        {
            T result = default(T);
            try
            {
                result = (T)HttpContext.Current.Session[cookieName];
            }
            catch { }
            return result;
        }
        public static void SaveSessionCookie(string cookieName, object cookieValue)
        {
            try
            {
                HttpContext.Current.Session.Add(cookieName, cookieValue);
            }
            catch { }
        }
    }
}
